import { createSignal, onMount, Show } from 'solid-js'
import styles from '../../styles/ui.module.css'
import { getCurrent, getPlayList } from '../../../utils/list'
import { checkPlay, getPlayer } from '../../../utils/player'
import { useGlobal } from '../status'

interface Status {
  name?: string;
  playerStatus?: jwplayer.PlayState;
  total?: number;
  doneCount?: number;
}

const palyStatusMap: Record<jwplayer.PlayState, string> = {
  buffering: '缓冲中',
  idle: '空闲',
  paused: '暂停',
  playing: '播放中',
}

let timer: any

export const Footer = () => {
  const [working, setWorking] = createSignal(false)
  const { updateSnapshot } = useGlobal()
  const [status, setStatus] = createSignal<Status>({})

  const updateStatus = () => {
    const current = getCurrent()
    const player = getPlayer()
    const list = getPlayList()
    setStatus({
      name: current?.name,
      done: current?.done,
      playerStatus: player?.getState() || 'idle',
      total: list.length,
      doneCount: list.filter((t) => t.done).length,
    })
  }

  const work = () => {
    updateStatus()
    checkPlay(updateSnapshot)
  }

  const handWork = (isWorking: boolean) => {
    console.log(isWorking ? '开始' : '停止')

    if (!isWorking) {
      setWorking(false)
      clearInterval(timer)
      return
    }

    if (isWorking) {
      work()
      timer = setInterval(work, 5000)
      setWorking(true)
    }
  }

  onMount(updateStatus)

  const handleRate = () => {
    const player = getPlayer()
    player?.setPlaybackRate(2)
  }

  return (
    <div class={styles.panelFooter}>
      <Show when={working()}>
        <div class={`${styles.panelFooterCard}`}>
          <div>
            当前：{status().name} &nbsp; 状态：
            {palyStatusMap[status().playerStatus]}
          </div>
          <div>
            总进度：{status().doneCount} / {status().total}
          </div>
          <div>{working() ? '工作中...' : '已停止监听'}</div>
        </div>
      </Show>

      <div class={`${styles.panelFooterCard} ${styles.panelFooterController}`}>
        <Show when={!working()}>
          <button onClick={() => handWork(true)}>开始</button>
          <span>&nbsp;</span>
        </Show>
        <Show when={working()}>
          <button onClick={() => handWork(false)}>停止监听</button>
          <span>&nbsp;</span>
          <button onClick={handleRate}>设置2倍速</button>
        </Show>
      </div>
      <div>官方限制了，最高速度只能是2，再高会被踢出去。。</div>
    </div>
  )
}
